import api from "../../config/api"
import request from "../../utils/request"
import { jump,setStorage } from "../../utils/utils"
const app = getApp()

// components/postList/index.js
Component({
  /**
   * 外部增加class
   */
  externalClasses: ['class'],
  /**
   * 组件的属性列表
   */
  properties: {
    // 帖子列表数据
    list: {
      type: Array,
      value: [],
    },
    // 帖子列表是否加载完成
    isDone: {
      type: Boolean,
      value: false,
    },
    // 当前页面名称: home: 个人中心 circle: 圈子主页 circleHome: 圈子首页
    page: {
      type: String,
      value: 'circle',
    },
    // 帖子列表是精选
    isFeatured: {
      type: Boolean,
      value: false,
    },
    // 是否是圈主
    owner: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  ready: function () {
    this.deleteModal = this.selectComponent('#deleteModal')
    this.followModal = this.selectComponent('#followModal')
    this.sheet = this.selectComponent('#sheet')
  },
  /**
   * 组件的方法列表
   */
  methods: {
      // 通过分享进入验证登录
  checkIsLogin(){
    const {page} = this.data
    if ((page==='circle'||page==='circleHome')&&(!app.isLogin())) {
      let path = page==='circle'?'/pages/circle/circle':'/pages/circleHome/circleHome'
      setStorage('redirectPath', path)
      app.login()
      return true
    }else{
      return false
    }
  },
    // 跳转到圈子主页
    async jumpCircle(e) {
      let check = this.checkIsLogin()
      console.log('详情check',check);
      if(check){
        return
      }

      if (this.loading) return
      this.loading = true
      const id = e?.currentTarget?.dataset?.id
      const res = await request.get(api.circleDetail, { id }, { loading: false })
      if (!res?.data?.allow) {
        wx.showToast({
          icon: 'none',
          title: '抱歉，您没有访问权限',
          duration: 2000
        })
      } else {
        jump('circle', { id })
      }
      this.loading = false
    },
    // 跳转到个人中心
    jumpHome(e) {
      let check = this.checkIsLogin()
      if(check){
        return
      }

      // 如果已经是个人中心不跳转
      if (this.data.page !== 'home') {
        jump('home', {
          id: e?.currentTarget?.dataset?.userid
        })
      }
    },
    // 跳转到帖子详情页面
    jumpPostDetail(e) {
      let check = this.checkIsLogin()
      if(check){
        return
      }

      const item = e?.currentTarget?.dataset?.item
      jump('postDetail', {
        circleId: item?.circleId,
        postId: item?.id
      })
    },
    // 跳转到帖子详情页面-发帖状态
    jumpPostStatus(e) {
      let check = this.checkIsLogin()
      if(check){
        return
      }

      const item = e?.currentTarget?.dataset?.item
      jump('postDetail', {
        circleId: item?.circleId,
        postId: item?.id,
        isPost: true
      })
    },
    // 点赞
    async like(e) {
      let check = this.checkIsLogin()
      if(check){
        return
      }

      if (this.loading) return
      this.loading = true
      const dataset = e?.currentTarget?.dataset
      const likedId = dataset?.id
      const res = await request.post(api.likePostOrComment, {
        likedId,
        type: 1,
        ...(dataset?.like ? { deleted: 1 } : {})
      }, { loading: false })
      if (res?.httpStatus === 200 || res?.msg === '已点赞') {
        this.setData({
          list: this.data.list.map(item => {
            if (item.id === likedId) {
              if (!item.like) {
                item.like = true
                item.likes += 1
              } else {
                item.like = false,
                  item.likes -= 1
              }
            }
            return item
          }),
        }, () => {
          this.loading = false
        })
        setTimeout(() => {
          wx.showToast({
            icon: 'none',
            title: dataset?.like ? '已取消' : '已点赞',
          })
        })
      } else {
        this.loading = false
      }
    },
    // 关注&取关用户
    async followUser(e) {
      if (this.loading) return
      this.loading = true
      const info = e?.currentTarget?.dataset?.item || this.info
      if (info.follow && e !== false) {
        this.info = info
        this.loading = false
        this.followModal.show()
        return
      }
      const res = await request.post(
        (info.follow ? api.cancleFollow : api.follow) + info?.userId,
        null,
        { loading: false }
      )
      if (res?.httpStatus === 200 || res?.msg === '已关注') {
        this.setData({
          list: this.data.list.map(item => {
            if (item.userId === info?.userId) {
              if (!item.follow) {
                item.follow = true
              } else {
                item.follow = false
              }
            }
            return item
          }),
        }, () => {
          this.loading = false
        })
        setTimeout(() => {
          wx.showToast({
            icon: 'none',
            title: info.follow ? '取消成功' : '关注成功',
          })
        })
        this.followModal.hide()
      } else {
        this.loading = false
      }
      this.info = null
    },
    // 设为精选&取消精选
    async featured(e) {
      if (this.loading) return
      this.loading = true
      const dataset = e?.currentTarget?.dataset?.item
      const res = await request.post(api.postDelete, {
        id: dataset?.id,
        featured: dataset?.featured ? 0 : 1,
      }, { loading: false })
      if (res?.httpStatus === 200 || res?.data) {
        this.setData({
          item: null,
          list: this.data.list.map(item => {
            if (item.id === dataset?.id) {
              if (!item.featured) {
                item.featured = 1
              } else {
                item.featured = 0
              }
            }
            return item
          }).filter(item => {
            return (this.data.isFeatured && item.id === dataset?.id) ? !!item.featured : true
          }),
        }, () => {
          this.loading = false
        })
        setTimeout(() => {
          wx.showToast({
            icon: 'none',
            title: dataset?.featured ? '已取消精选' : '已设为精选',
          })
        })
        this.sheet.hide()
      } else {
        this.loading = false
      }
    },
    // 取关确认
    followConfirm() {
      this.followUser(false)
    },
    // 删除提示框
    deleteTip() {
      this.deleteModal.show()
    },
    // 删除帖子
    async deletePost() {
      const id = this.data.item?.id
      if (!id) return
      if (this.loading) return
      this.loading = true
      const isHome = this.data.page === 'home'
      const res = await request.post(isHome ? `${api.postDeleteOnly}/${id}` : api.postDelete, {
        id,
        deleted: 1
      })
      if (res?.httpStatus === 200) {
        this.setData({
          list: this.data.list.filter(item => {
            return item.id !== id
          })
        })
        this.deleteModal.hide()
        this.sheet.hide()
        setTimeout(() => {
          wx.showToast({
            icon: 'none',
            title: '删除成功',
          })
        })
      } else {
        this.deleteModal.hide()
      }
      this.loading = false
      
    },
    // 打开操作弹窗
    showSheet(e) {
      const item = e?.currentTarget?.dataset?.item
      this.setData({
        item
      })
      this.sheet.show()
    },
    // 关闭操作弹窗
    hideSheet() {
      this.setData({
        item: null
      })
      this.sheet.hide()
    },
    // 取消滑动事件
    catchtouchmove() {
      return
    },
    // 点击分享图标
    handleShare(e){
      let detail = e.currentTarget.dataset.item
      let imageUrl = ''
      if(detail.shareType>2||detail.shareType==2){
        imageUrl = detail.picUrls[1]
      }else{
        imageUrl = detail.picUrls[0]||'https://image-classify.daieco.com/kejian-quanzi/qpUkToC5kE4bffc4952cbd9cd5b16b5ec0863e5c733e.png'
      }
      let title = detail.content.length>12?detail.content.substring(0,14)+'...':detail.content
      let path = `/pages/postDetail/postDetail?postId=${detail.id}&fromShare=true`

      this.triggerEvent("name",{ title: title, imageUrl: imageUrl, path: path })
    },
  },
})
